//Registers a service


package jbpClientTester;

import com.apple.dnssd.DNSSD;
import com.apple.dnssd.DNSSDException;
import com.apple.dnssd.DNSSDRegistration;
import com.apple.dnssd.DNSSDService;
import com.apple.dnssd.RegisterListener;
import com.apple.dnssd.TXTRecord;

public class ServiceRegistrar implements RegisterListener
{
	private static String name;
	private static String service;
	private boolean successful;
	private DNSSDRegistration reg;
	
	public ServiceRegistrar (String argName, String serviceName, int port)
	throws DNSSDException, InterruptedException
	{
		service = serviceName;
		name = argName;
		successful = false;
		
		System.out.println("Registration starting...");
		/*
		System.out.println("Requested Name: " + name);
		System.out.println("		Service: " + service);
		System.out.println("		Port: " + port);
		*/

		TXTRecord txtRecord = new TXTRecord(  );
		txtRecord.set("txtvers", "1");
		txtRecord.set("status", "ready");
		txtRecord.set("difficulty", "medium");

		

		/*for (int i = 0; i < txtRecord.size(  ); i++)
		{
			String key = txtRecord.getKey(i);
			String value = txtRecord.getValueAsString(i);
			if (key.length() > 0)
				System.out.println("     *** " + key + "=" + value);
		}*/

		reg = DNSSD.register(0, DNSSD.ALL_INTERFACES,
				name, service, null,  // Name, type, and domain
				null, port,                   // Target host and port
				txtRecord, this);             // TXT record and listener object

	}

	// Method inherited from RegisterListener: failure
	public void operationFailed(DNSSDService service, int errorCode)
	{
		System.err.println("Registration failed " + errorCode);
	}

	// Method inherited from RegisterListener: success
	public void serviceRegistered(DNSSDRegistration registration, int flags,
			String serviceName, String regType, String domain)
	{
		System.out.println("Registered Name  : " + serviceName);
		/*System.out.println("           Type  : " + regType);
		System.out.println("           Domain: " + domain);*/
		successful = true;
	}
	
	public boolean isRegistered(){
		return successful;
	}
	
	public void killRegistration(){
		System.out.println("Stopping registration.");
		reg.stop();
	}
}
